package com.cssy.xxkj.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.contants.Constants;
import com.cssy.xxkj.logic.dao.LogicProductionGetDAO;
import com.cssy.xxkj.logic.dao.LogicProductionGetItemDAO;
import com.cssy.xxkj.logic.dao.LogicProductionPlanDAO;
import com.cssy.xxkj.logic.dao.LogicProductionPlanItemDAO;
import com.cssy.xxkj.logic.dao.SystemLogDAO;
import com.cssy.xxkj.logic.entity.LogicProductionGetDO;
import com.cssy.xxkj.logic.entity.LogicProductionGetItemDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanDO;
import com.cssy.xxkj.logic.entity.LogicProductionPlanItemDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseDetailsDO;
import com.cssy.xxkj.logic.service.ILogicProductionGetService;
import com.cssy.xxkj.logic.service.ILogicWarehouseInventoryService;
import com.cssy.yd.logic.util.MathUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
/**
 * 生产领料业务方法
 * @modify hf 
 *
 */
@Service("logicProductionGetService")
public class LogicProductionGetServiceImpl implements ILogicProductionGetService {
	private static final Logger logger = Logger.getLogger(LogicProductionGetServiceImpl.class);
	@Resource(name = "logicProductionGetDAO")
	private LogicProductionGetDAO logicProductionGetDAO;
	//生产计划Service
	@Resource(name = "logicProductionPlanDAO")
	private LogicProductionPlanDAO logicProductionPlanDAO;
	//生产计划Service
	@Resource(name = "logicProductionPlanItemDAO")
	private LogicProductionPlanItemDAO logicProductionPlanItemDAO;
	
	@Resource(name = "logicProductionGetItemDAO")
	private LogicProductionGetItemDAO  logicProductionGetItemDAO;
	
	@Resource(name = "logicWarehouseInventoryService")
	private ILogicWarehouseInventoryService logicWarehouseInventoryService;
	
	@Resource(name = "systemLogDAO")
	private SystemLogDAO systemLogDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicProductionGetDO>  list=logicProductionGetDAO.find(scs);
		rs.setRecordCount(logicProductionGetDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		logicProductionGetDAO.deleteLogicProductionGetDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicProductionGetDO t, User user) throws SyBaseException {
		t.setBizModifyName(user.getName());
		t.setBizModifyDate(new Date());
		t.setBizVersionMark(t.getBizVersion());
		t.setBizVersion(t.getBizVersion()+1);
		return logicProductionGetDAO.updateLogicProductionGetDO(t);
	}

	@Override
	public LogicProductionGetDO save(LogicProductionGetDO sodo, User user) throws SyBaseException {
		sodo.setBizCreatorName(user.getName());
		sodo.setBizCreatorDate(new Date());
		sodo.setBizVersion(1);
		logicProductionGetDAO.insertLogicProductionGetDO(sodo);
		return sodo;
	}

	@Override
	public LogicProductionGetDO findListById(String id) throws SyBaseException {
		return logicProductionGetDAO.findLogicProductionGetDOByPrimaryKey(id);
	}


	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		return logicProductionGetDAO.deleteBizRemoved(id);
	}

	

	@Override
	public List<LogicProductionGetItemDO> findGetItemList(String id) throws SyBaseException {
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd001GetId", id, SearchCondition.OP_EQUAL);
		List<LogicProductionGetItemDO>  list=logicProductionGetItemDAO.find(scs);
		return list;
	}

	@Override
	public void dispatSave(HttpServletRequest request, LogicProductionGetDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("itemdata");//物品数据
			String paramflag =request.getParameter("paramflag");
			
			curAP.setZd011BillStatus(paramflag);//单据状态
			List<LogicProductionGetItemDO> Itemlist = JSONArray.parseArray(itemdata,LogicProductionGetItemDO.class);
			User user = SessionUtil.getUser(request);
			boolean ba=true;
			if (StringUtils.isBlank(curAP.getId())) {
					String id = IDCodeTypeUtil.getId();
					curAP.setId(id);
					curAP.setZd001GetCode(syCodeService.getCode(BillTypeConstant.PROGET,BillTypeConstant.PROGET,SyCode.DATE_YYMM,5));
					//日期转换处理
					String zd010OtherDate = request.getParameter("zd010OtherDate");//出库日期
					if(StringUtils.isNotBlank(zd010OtherDate)){
						curAP.setZd010OtherDate(DateUtils.stringToDate(zd010OtherDate));
					}
					curAP.setZd017ReturnStastus(0l);
					this.save(curAP,user);
					for (LogicProductionGetItemDO ItemDO : Itemlist) {
						ItemDO.setZd001GetId(id);
						ItemDO.setId(IDCodeTypeUtil.getId());
						logicProductionGetItemDAO.insertLogicProductionGetItemDO(ItemDO);
					}
					logger.info("新增生产领料单成功");
			} else {
				if(!curAP.getZd011BillStatus().equals(BillStatusUtil.PROGET_STATUS_FIVE)){
						String zd010OtherDate =request.getParameter("zd010OtherDate");
						curAP.setZd010OtherDate(DateUtils.stringToDate(zd010OtherDate));
						int rt=0;
						rt=this.update(curAP, SessionUtil.getUser(request));
						if(0==rt){
							throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
						}
						if(Itemlist!=null&&!Itemlist.isEmpty()&&Itemlist.size()>0){
							List<LogicProductionGetItemDO> list = findByIdItem(curAP,true);
							logicProductionGetItemDAO.deleteProById(curAP.getId());
							for(int i=0;i<Itemlist.size();i++){
								if(this.validateSubmit(list, Itemlist.get(i))){
									throw new SyBaseException("订单物料”"+Itemlist.get(i).getZd002MaterialsName()+"“下单总数量大于订单数量，不合法！");
								}
								Itemlist.get(i).setZd001GetId(curAP.getId());
								Itemlist.get(i).setId(IDCodeTypeUtil.getId());
								logicProductionGetItemDAO.insertLogicProductionGetItemDO(Itemlist.get(i));
							}
						}
					}
					if (curAP.getZd011BillStatus().equals(BillStatusUtil.PROGET_STATUS_FIVE)){
						int rt=0;
						rt=this.update(curAP, SessionUtil.getUser(request));
						if(0==rt){
							throw new SyBaseException("您操作的单据数据发生了改变!请您重新打开编辑！");
						}
						LogicProductionGetDO loi = logicProductionGetDAO.findLogicProductionGetDOByPrimaryKey(curAP.getId());
						for (LogicProductionGetItemDO lii : Itemlist){
							LogicWarehouseDetailsDO lw = new LogicWarehouseDetailsDO();
							lw.setZd001BillCode(loi.getZd001GetCode());
							lw.setZd019Batch(Constants.SYS_DEFAULT_BATCH);
							lw.setZd002BillType(BillTypeConstant.PROGET);
							lw.setZd005MaterialsId(lii.getZd002MaterialsId());
							lw.setZd005MaterialsCode(lii.getZd002MaterialsCode());
							lw.setZd005MaterialsName(lii.getZd002MaterialsName());
							lw.setZd006MaterialsSpec(lii.getZd003MaterialsSpec());
							lw.setZd007MaterialsModel(lii.getZd004MaterialsModel());
							lw.setZd009BasicUnit(lii.getZd006Unit());
							lw.setZd012Status(lii.getZd008Status());
							lw.setZd004WhPositionId(lii.getZd011WhLocationId());
							lw.setZd004WhPositionCode(lii.getZd012WhLocationCode());
							lw.setZd003WhId(loi.getZd004Whid());
							lw.setZd003WhCode(loi.getZd004WhCode());
							lw.setZd003WhName(loi.getZd004WhName());
							lw.setBizCreatorName(SessionUtil.getUser(request).getName());
							lw.setBizCreatorDate(new Date());
							lw.setZd011BasicQuantity(lii.getZd007Quantity().negate());
							logicWarehouseInventoryService.updateWhAffstockQuantity(lw, SessionUtil.getUser(request),false);
						}
					logger.info("修改生产领料单成功");
			}
			if(curAP.getZd011BillStatus().equals(BillStatusUtil.PROGET_STATUS_FIVE)){
				LogicProductionPlanDO plan = new LogicProductionPlanDO();
				plan.setZd001FormCode(curAP.getZd002OriCode());
				List<LogicProductionPlanDO> planlist=logicProductionPlanDAO.findListByExample(plan);
				if(planlist!=null&&!planlist.isEmpty()&&planlist.size()>0){
					if(this.validateGet(this.findByIdItem(curAP,false), planlist.get(0).getId())){
						planlist.get(0).setZd013WhGetStatus(2l);
					}else{
						planlist.get(0).setZd013WhGetStatus(1l);
					}
					planlist.get(0).setBizVersionMark(planlist.get(0).getBizVersion());
					planlist.get(0).setBizVersion(planlist.get(0).getBizVersion()+1);
					int lp=logicProductionPlanDAO.updateLogicProductionPlanDO(planlist.get(0));
					if(lp==0){
						throw new SyBaseException("生产计划单数据发生改变！无法完成当前操作，请关闭当前页重试！");
					}
					logger.info("更新生产计划单领料状态成功");
				}
			}
		}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("操作生产领料单失败！");
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+e.getMessage());
		}
	}
	
	/**
	 * 验证出库数量是否合法
	 * @param list
	 * @param ItemDO
	 * @return
	 */
	private boolean validateSubmit(List<LogicProductionGetItemDO> list,LogicProductionGetItemDO ItemDO){
		BigDecimal bg = MathUtil.mathUtil.multiply(ItemDO.getZd018PlanQuantity(), ItemDO.getZd019BomQuantity());
		if(list!=null&&!list.isEmpty()&&list.size()>0){
			for(int i=0;i<list.size();i++){
				if(ItemDO.getZd002MaterialsCode().equals(list.get(i).getZd002MaterialsCode())){
					bg=MathUtil.mathUtil.subtract(bg, list.get(i).getZd007Quantity());
				}
			}
		}
		if(bg.compareTo(new BigDecimal(0))==1){
			return false;
		}
		return true;
	}
	
	private List<LogicProductionGetItemDO> findByIdItem(LogicProductionGetDO curAP,boolean bl){
		List<LogicProductionGetItemDO> list = new ArrayList<LogicProductionGetItemDO>();
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty("removed");
		if(bl){
			scs.addCondition("zd001GetCode", curAP.getZd001GetCode(), SearchCondition.OP_NOTEQUAL);
		}
		scs.addCondition("zd002OriCode", curAP.getZd002OriCode(), SearchCondition.OP_EQUAL);
		scs.addCondition("zd011BillStatus", BillStatusUtil.PROGET_STATUS_FIVE, SearchCondition.OP_EQUAL);
		List<LogicProductionGetDO> result = this.findListByExample(scs).getResults();
		if(result!=null&&!result.isEmpty()&&result.size()>0){
			for(int i=0;i<result.size();i++){
				List<LogicProductionGetItemDO> dispatItem = this.findGetItemList(result.get(i).getId());
				list.addAll(dispatItem);
			}
		}
		return list;
	}
	
	/**
	 * 验证是否已经全部领料完成
	 * @param list
	 * @param planId
	 * @return
	 */
	private boolean validateGet(List<LogicProductionGetItemDO> list,String planId){
		LogicProductionPlanItemDO planitem = new LogicProductionPlanItemDO();
		planitem.setZd001ProPlanId(planId);
		List<LogicProductionPlanItemDO> planitemlist=logicProductionPlanItemDAO.findListByExample(planitem);
		boolean bl =true;//是否全部使用完成
		for(int n=0;n<planitemlist.size();n++){
			BigDecimal bd = planitemlist.get(n).getZd013Quantity();
			for(int i=0;i<list.size();i++){
				if(planitemlist.get(n).getZd007MaterialsCode().equals(list.get(i).getZd002MaterialsCode())){
					bd=MathUtil.mathUtil.subtract(bd, list.get(i).getZd007Quantity());	
				}
			}
			if(bd.compareTo(new BigDecimal(0))==1){
				bl=false;
			}
		}
		return bl;
	}
}
